<template>
  <div class="icon-body">
    <el-input
        v-model="iconName"
        class="icon-search"
        clearable
        placeholder="请输入图标名称"
        @clear="filterIcons"
        @input="filterIcons"
    >
      <template #suffix><i class="el-icon-search el-input__icon" /></template>
    </el-input>
    <div class="icon-list">
      <div class="list-container">
        <div v-for="(item, index) in iconList" class="icon-item-wrapper" :key="index" @click="selectedIcon(item.name)">
          <div :class="['icon-item', { active: activeIcon === item.name }]">
            <el-icon :size="20" :color="activeIcon === item.name ? '#409EFF' : '#909399'">
              <component :is="item.component" />
            </el-icon>
            <span>{{ item.name }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

const props = defineProps({
  activeIcon: {
    type: String
  }
})

const iconName = ref('')
const iconList = ref([])
const emit = defineEmits(['selected'])
function filterIcons() {
  if (iconName.value) {
    iconList.value = iconList.value.filter(item =>
        item.name.toLowerCase().includes(iconName.value.toLowerCase())
    )
  } else {
    iconList.value = []
  }
}

function selectedIcon(name) {

  emit('selected', name)
  document.body.click()
}

function reset() {
  iconName.value = ''
  const icons = []
  for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    icons.push({
      name: key,
      component: component
    })
  }
  iconList.value = icons
}

defineExpose({
  reset
})
</script>

<style lang='scss' scoped>
.icon-body {
  width: 100%;
  padding: 10px;

  .icon-search {
    position: relative;
    margin-bottom: 5px;

    .el-input__inner {
      padding: 8px 35px 8px 10px;
    }
  }

  .icon-list {
    height: 200px;
    overflow: auto;

    .list-container {
      display: flex;
      flex-wrap: wrap;

      .icon-item-wrapper {
        width: calc(100% / 4); // 增加每行显示数量
        height: 40px;
        line-height: 40px;
        cursor: pointer;
        display: flex;
        align-items: center;
        padding: 0 8px;

        .icon-item {
          display: flex;
          align-items: center;
          gap: 8px;
          width: 100%;
          height: 100%;
          padding: 0 5px;

          &:hover {
            background: #f5f7fa;
            border-radius: 4px;
          }

          .el-icon {
            font-size: 20px;
          }

          span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .icon-item.active {
          background: #ecf5ff;
          border-radius: 4px;
        }
      }
    }
  }
}
</style>
